<template>
	<view class="custom-slider">
		<view class="slider-bar" @tap="handleToTap" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
			@touchend="handleTouchEnd">
			<view class="slider-button" :style="{left: buttonLeft + '%'}">
				<!-- 这里可以放一个自定义的滑块图标 -->
				<image class="slider-handle" src="https://www.hzif.cn/mathematics-attach/huakuai.png" mode=""></image>
			</view>
		</view>
		<view class="activeBar" :style="{width:buttonLeft+10+'%'}">
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				buttonLeft: 10, // 滑块的初始位置
			};
		},
		watch: {
			btnInit: {
				immediate: true,
				handler(val) {
					if (this.typeNum === 'thousand') {
						this.buttonLeft = Math.round(val / 10) -10
					} else {
						this.buttonLeft = val
					}
				}
			}
		},
		methods: {
			handleToTap(e) {
				// console.log(e);
			},
			handleTouchStart(e) {},
			handleTouchMove(event) {
				// 处理触摸移动事件，更新滑块位置
				const touch = event.touches[0];
				const sliderBarWidth = 150;
				let newLeft = touch.clientX - 160;
				// console.log(newLeft);
				if (newLeft >= 0 && newLeft <= 130) {
					this.buttonLeft = Number(parseFloat((newLeft / 150) * 100).toFixed(0));
					// 这里可以触发自定义的事件，将滑块的值发送给父组件
					this.$emit('updateValue', this.calculateValue(this.buttonLeft));
				}
			},
			handleTouchEnd(e) {
				this.$emit('checkedValue', this.calculateValue(this.buttonLeft));
			},
			calculateValue(left) {
				// 将滑块位置转换为对应的值
				const sliderBarWidth = 130;
				const sliderRange = (this.max - this.min);
				let num = Math.floor((left / sliderBarWidth) * sliderRange * 1.5 + this.min)
				return num>1000?1000:num;
			}
		},
		props: {
			btnInit: {
				type: Number,
				default: 10
			},
			min: {
				type: Number,
				default: 0
			},
			max: {
				type: Number,
				default: 100
			},
			value: {
				type: Number,
				default: 10
			},
			typeNum: {
				type: String,
				default: 'ten'
			}
		}
	};
</script>

<style scoped>
	.custom-slider {
		position: relative;
		/* 设置滑块的高度 */
		height: 40px;
		display: flex;
		align-items: center;
		width: 300rpx;
	}

	.slider-bar {
		position: relative;
		/* 设置滑块轨道的高度,宽度 */
		height: 15rpx;
		width: 300rpx;
		/* 设置轨道的颜色 */
		background-color: #DFF6DE;
		box-shadow: 0rpx 2rpx 3rpx 0rpx rgba(132, 183, 129, 0.36);
		border-radius: 8rpx;
	}

	.activeBar {
		background: linear-gradient(90deg, #59F2CC, #2E996C);
		position: absolute;
		height: 15rpx;
		border-radius: 8rpx;
	}

	.slider-button {
		position: absolute;
		user-select: none;
		left: 0px;
		top: -5px;
		/* 初始位置 */
		width: 44rpx;
		/* 设置滑块的宽度 */
		height: 44rpx;
		/* 设置滑块的高度 */
		cursor: pointer;
		border-radius: 50%;
		/* 滑块设置为圆形 */
		z-index: 10;

	}

	.slider-handle {
		user-select: none;
		width: 43rpx;
		height: 43rpx;
	}
</style>